package com.xzh.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.rabbitmq.client.Channel;
import com.xzh.common.to.mq.OrderTo;
import com.xzh.common.to.mq.StockDetailTo;
import com.xzh.common.to.mq.StockLockedTo;
import com.xzh.common.utils.R;
import com.xzh.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.xzh.gulimall.ware.entity.WareOrderTaskEntity;
import com.xzh.gulimall.ware.service.WareSkuService;
import com.xzh.gulimall.ware.vo.OrderVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;
    /*1、库存自动解锁
     * 下订单成功，库存锁定成功，但是接下来的业务调用失败导致订单回滚，之前锁定的库存就要自动解锁 */

    /*只要解锁库存的消息失败，一定要告诉服务器解锁失败（开启手动ACK)*/
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息===");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);

        }


    }
    //订单关闭的处理
    @RabbitHandler
    public void handOrderClosedRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭，准备解锁库存===");
        try{
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
}
